<template>
    <div></div>
</template>

<script>
    import api from "@/utils/api";
    import axios from "axios";

    export default {
        name: "login",
        data() {
            return {
                APPID: "wx6580046b0e1b14ee"
            };
        },
        mounted() {
            // this.getCode();
            this.getUrl();
        },
        methods: {
            getCode() {
                var code = this.getUrlParam("code");
                var local = location.href;
                local = local.split("#")[0];
                console.log(code);
                if (!code) {
                    location.href =
                        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
                        this.APPID +
                        "&redirect_uri=" +
                        encodeURIComponent(local) +
                        "&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
                } else {
                    console.log("进入code:" + code)
                    this.login(code);
                }
            },
            // getUrl() {
            //   console.log("进入getUrl")
            //   const instance = axios.create({});
            //   instance({
            //     method: "get",
            //     url: api.geturl
            //   }).then(res => {
            //     console.log(res);
            //     location.href = res.data.url;
            //   });
            // },

            getUrl() {
                console.log("进入getUrl");
                this.$axios.get(api.geturl).then(res => {
                    console.log(res);
                    location.href = res.url;
                });
            },

            login(code) {
                console.log("进入login：" + code);
                // const instance = axios.create({});
                this.$axios.get(api.wxlogin, {
                    params: {
                        code: code
                    }
                })
                    .then(res => {
                        console.log(res);
                        // this.$toast(res.msg);
                        // if (res.code == 200) {
                        localStorage.setItem("token", res.token);
                        this.$router.push("/");
                        // }
                    });
            },
            getUrlParam(name) {
                //封装方法
                var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
                var r = window.location.search.substr(1).match(reg); //匹配目标参数
                if (r != null) return unescape(r[2]);
                return null; //返回参数值
            }
        }
    };
</script>

<style lang="less" scoped>
</style>

